import React, { useState, useEffect } from 'react';
import { Table, Input, Button, DatePicker, Card, Space, Tag, Select } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import * as XLSX from 'xlsx';
import ReactECharts from 'echarts-for-react';
import OverviewLayout from '../../layouts/OverviewLayout';
import moment from 'moment';

const { Option } = Select;

// 模拟项目数据
const mockProjects = [
    { id: 'P001', name: '城市花园项目', budget: 5000000 },
    { id: 'P002', name: '商业中心建设', budget: 8000000 },
    { id: 'P003', name: '地铁延长线工程', budget: 12000000 },
];

// 模拟费用数据
const mockExpenses = [
    {
        id: 'EXP2023001',
        projectId: 'P001',
        projectName: '城市花园项目',
        category: '材料费',
        subCategory: '钢筋',
        amount: 480000,
        paymentDate: '2023-01-25',
        paymentMethod: '银行转账',
        payer: '财务部-张三',
        recipient: '建材供应商A',
        contractId: 'CON2023001',
        invoiceNumber: 'INV20230001',
        status: '已支付',
        approvalStatus: '已审批',
        remark: '一期工程材料款'
    },
    {
        id: 'EXP2023002',
        projectId: 'P001',
        projectName: '城市花园项目',
        category: '人工费',
        subCategory: '施工队工资',
        amount: 320000,
        paymentDate: '2023-02-10',
        paymentMethod: '银行转账',
        payer: '财务部-李四',
        recipient: '第一施工队',
        contractId: 'CON2023002',
        invoiceNumber: 'INV20230002',
        status: '已支付',
        approvalStatus: '已审批',
        remark: '1月份工资'
    },
    {
        id: 'EXP2023003',
        projectId: 'P001',
        projectName: '城市花园项目',
        category: '设备租赁',
        subCategory: '起重机',
        amount: 150000,
        paymentDate: '2023-02-15',
        paymentMethod: '银行转账',
        payer: '财务部-王五',
        recipient: '设备租赁公司B',
        contractId: 'CON2023003',
        invoiceNumber: 'INV20230003',
        status: '已支付',
        approvalStatus: '已审批',
        remark: '2月份租赁费'
    },
    {
        id: 'EXP2023004',
        projectId: 'P002',
        projectName: '商业中心建设',
        category: '材料费',
        subCategory: '混凝土',
        amount: 600000,
        paymentDate: '2023-03-10',
        paymentMethod: '银行转账',
        payer: '财务部-赵六',
        recipient: '混凝土供应商C',
        contractId: 'CON2023004',
        invoiceNumber: 'INV20230004',
        status: '已支付',
        approvalStatus: '已审批',
        remark: '主体结构材料'
    },
    {
        id: 'EXP2023005',
        projectId: 'P002',
        projectName: '商业中心建设',
        category: '设计费',
        subCategory: '施工图设计',
        amount: 250000,
        paymentDate: '2023-03-20',
        paymentMethod: '银行转账',
        payer: '财务部-钱七',
        recipient: '设计院D',
        contractId: 'CON2023005',
        invoiceNumber: 'INV20230005',
        status: '已支付',
        approvalStatus: '已审批',
        remark: '施工图设计费'
    },
    {
        id: 'EXP2023006',
        projectId: 'P003',
        projectName: '地铁延长线工程',
        category: '材料费',
        subCategory: '钢材',
        amount: 850000,
        paymentDate: '2023-04-05',
        paymentMethod: '银行转账',
        payer: '财务部-孙八',
        recipient: '钢材供应商E',
        contractId: 'CON2023006',
        invoiceNumber: 'INV20230006',
        status: '已支付',
        approvalStatus: '已审批',
        remark: '地下部分钢材'
    }
];

const ProjectExpenseOverview = () => {
    const [selectedProject, setSelectedProject] = useState(null);
    const [expenses, setExpenses] = useState([]);
    const [filteredExpenses, setFilteredExpenses] = useState([]);
    const [filters, setFilters] = useState({
        category: '',
        subCategory: '',
        status: '',
        startDate: null,
        endDate: null
    });

    // 根据选择的项目筛选费用
    useEffect(() => {
        if (selectedProject) {
            const filtered = mockExpenses.filter(exp => exp.projectId === selectedProject);
            setExpenses(filtered);
            setFilteredExpenses(filtered);
        } else {
            setExpenses([]);
            setFilteredExpenses([]);
        }
    }, [selectedProject]);

    // 处理筛选变化
    const handleFilterChange = (key, value) => {
        const newFilters = { ...filters, [key]: value };
        setFilters(newFilters);
        applyFilters(newFilters);
    };

    // 应用筛选条件
    const applyFilters = (filterParams) => {
        let result = [...expenses];

        if (filterParams.category) {
            result = result.filter(exp => exp.category.includes(filterParams.category));
        }

        if (filterParams.subCategory) {
            result = result.filter(exp => exp.subCategory.includes(filterParams.subCategory));
        }

        if (filterParams.status) {
            result = result.filter(exp => exp.status.includes(filterParams.status));
        }

        if (filterParams.startDate && filterParams.endDate) {
            result = result.filter(exp => {
                const paymentDate = moment(exp.paymentDate);
                return paymentDate.isAfter(filterParams.startDate) && paymentDate.isBefore(filterParams.endDate);
            });
        }

        setFilteredExpenses(result);
    };

    // 导出Excel
    const exportToExcel = () => {
        const worksheet = XLSX.utils.json_to_sheet(filteredExpenses);
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, "项目费用列表");
        XLSX.writeFile(workbook, `项目费用列表_${moment().format('YYYYMMDD_HHmmss')}.xlsx`);
    };

    // 获取当前项目的预算
    const getProjectBudget = () => {
        const project = mockProjects.find(p => p.id === selectedProject);
        return project ? project.budget : 0;
    };

    // 计算已支付总额
    const getTotalExpenses = () => {
        return filteredExpenses.reduce((sum, exp) => sum + exp.amount, 0);
    };

    // 计算预算使用率
    const getBudgetUsage = () => {
        const budget = getProjectBudget();
        if (budget === 0) return 0;
        return (getTotalExpenses() / budget * 100).toFixed(2);
    };

    // 图表配置 - 费用类别分布
    const expenseCategoryOption = {
        title: {
            text: '费用类别分布',
            left: 'center'
        },
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : ¥{c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            left: 'left',
            data: ['材料费', '人工费', '设备租赁', '设计费', '其他']
        },
        series: [
            {
                name: '费用类别',
                type: 'pie',
                radius: '55%',
                center: ['50%', '60%'],
                data: [
                    { value: 1930000, name: '材料费' },
                    { value: 320000, name: '人工费' },
                    { value: 150000, name: '设备租赁' },
                    { value: 250000, name: '设计费' },
                    { value: 80000, name: '其他' }
                ],
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    };

    // 图表配置 - 月度费用趋势
    const monthlyExpenseOption = {
        title: {
            text: '月度费用趋势',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                label: {
                    backgroundColor: '#6a7985'
                }
            },
            formatter: '{b}<br/>{a0}: ¥{c0}'
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月']
        },
        yAxis: {
            type: 'value',
            name: '金额(元)'
        },
        series: [
            {
                name: '费用支出',
                type: 'line',
                areaStyle: {},
                data: [480000, 470000, 600000, 850000, 720000, 680000, 550000],
                itemStyle: {
                    color: '#1890ff'
                }
            }
        ]
    };

    // 表格列配置
    const columns = [
        {
            title: '费用ID',
            dataIndex: 'id',
            key: 'id',
            width: 120,
            fixed: 'left'
        },
        {
            title: '费用类别',
            dataIndex: 'category',
            key: 'category',
            width: 120
        },
        {
            title: '子类别',
            dataIndex: 'subCategory',
            key: 'subCategory',
            width: 120
        },
        {
            title: '金额(元)',
            dataIndex: 'amount',
            key: 'amount',
            render: amount => `¥${amount.toLocaleString()}`,
            width: 120
        },
        {
            title: '支付日期',
            dataIndex: 'paymentDate',
            key: 'paymentDate',
            width: 120
        },
        {
            title: '支付方式',
            dataIndex: 'paymentMethod',
            key: 'paymentMethod',
            width: 120
        },
        {
            title: '付款人',
            dataIndex: 'payer',
            key: 'payer',
            width: 150
        },
        {
            title: '收款方',
            dataIndex: 'recipient',
            key: 'recipient',
            width: 150
        },
        {
            title: '合同编号',
            dataIndex: 'contractId',
            key: 'contractId',
            width: 120
        },
        {
            title: '发票号码',
            dataIndex: 'invoiceNumber',
            key: 'invoiceNumber',
            width: 120
        },
        {
            title: '支付状态',
            dataIndex: 'status',
            key: 'status',
            render: status => {
                let color = status === '已支付' ? 'green' : 'orange';
                return <Tag color={color}>{status}</Tag>;
            },
            width: 100
        },
        {
            title: '审批状态',
            dataIndex: 'approvalStatus',
            key: 'approvalStatus',
            render: status => {
                let color = status === '已审批' ? 'green' : status === '审批中' ? 'orange' : 'red';
                return <Tag color={color}>{status}</Tag>;
            },
            width: 100
        },
        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
            width: 150
        }
    ];

    return (
        <OverviewLayout
            children={{
                topRight:
                    <ReactECharts
                        option={expenseCategoryOption}
                        style={{ height: '100%', width: '100%' }}
                    />,
                topLeft:
                    <ReactECharts
                        option={monthlyExpenseOption}
                        style={{ height: '100%', width: '100%' }}
                    />,
                bottom:
                    <Card
                        title={
                            <Space>
                                <span>项目费用明细</span>
                                {selectedProject && (
                                    <Space>
                                        <Tag color="blue">项目预算: ¥{getProjectBudget().toLocaleString()}</Tag>
                                        <Tag color="green">已支付: ¥{getTotalExpenses().toLocaleString()}</Tag>
                                        <Tag color={getBudgetUsage() > 80 ? 'red' : 'orange'}>
                                            预算使用率: {getBudgetUsage()}%
                                        </Tag>
                                    </Space>
                                )}
                            </Space>
                        }
                        variant={"borderless"}
                        extra={
                            <Space>
                                <Select
                                    placeholder="选择项目"
                                    style={{ width: 200 }}
                                    onChange={(value) => setSelectedProject(value)}
                                    allowClear
                                >
                                    {mockProjects.map(project => (
                                        <Option key={project.id} value={project.id}>
                                            {project.name}
                                        </Option>
                                    ))}
                                </Select>
                                <Button
                                    type="primary"
                                    icon={<DownloadOutlined />}
                                    onClick={exportToExcel}
                                    disabled={!selectedProject}
                                >
                                    导出Excel
                                </Button>
                            </Space>
                        }
                    >
                        {selectedProject ? (
                            <>
                                <Space style={{ marginBottom: 16 }}>
                                    <Input
                                        placeholder="费用类别"
                                        value={filters.category}
                                        onChange={e => handleFilterChange('category', e.target.value)}
                                        style={{ width: 150 }}
                                    />
                                    <Input
                                        placeholder="子类别"
                                        value={filters.subCategory}
                                        onChange={e => handleFilterChange('subCategory', e.target.value)}
                                        style={{ width: 150 }}
                                    />
                                    <Input
                                        placeholder="支付状态"
                                        value={filters.status}
                                        onChange={e => handleFilterChange('status', e.target.value)}
                                        style={{ width: 150 }}
                                    />
                                    <DatePicker.RangePicker
                                        value={[filters.startDate, filters.endDate]}
                                        onChange={(dates) => {
                                            handleFilterChange('startDate', dates ? dates[0] : null);
                                            handleFilterChange('endDate', dates ? dates[1] : null);
                                        }}
                                    />
                                    <Button
                                        type="default"
                                        onClick={() => {
                                            setFilters({
                                                category: '',
                                                subCategory: '',
                                                status: '',
                                                startDate: null,
                                                endDate: null
                                            });
                                            setFilteredExpenses(expenses);
                                        }}
                                    >
                                        重置
                                    </Button>
                                </Space>
                                <Table
                                    columns={columns}
                                    dataSource={filteredExpenses}
                                    rowKey="id"
                                    pagination={{ pageSize: 10 }}
                                    scroll={{ x: 2000 }}
                                />
                            </>
                        ) : (
                            <div style={{ textAlign: 'center', padding: '50px 0' }}>
                                <h3>请先选择项目查看费用信息</h3>
                            </div>
                        )}
                    </Card>
            }}
        />
    );
};

export default ProjectExpenseOverview;